﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;

namespace Babylon.Toolbox
{
    public partial class Scene
    {
        public ObservableCollection<ParticleSystem> ParticleSystems { get; private set; }
        public ObservableCollection<SceneObject> Objects { get; private set; }
        readonly List<SceneObject> opaqueObjects = new List<SceneObject>();
        readonly List<SceneObject> alphaBlendedObjects = new List<SceneObject>();

        void AddOrCheckSceneObjectToCorrectList(SceneObject sceneObject)
        {
            if (opaqueObjects.Contains(sceneObject))
            {
                if (!sceneObject.NeedAlphaBlending)
                    return;
                opaqueObjects.Remove(sceneObject);
            }

            if (alphaBlendedObjects.Contains(sceneObject))
            {
                if (sceneObject.NeedAlphaBlending)
                    return;
                alphaBlendedObjects.Remove(sceneObject);
            }

            if (sceneObject.NeedAlphaBlending)
                alphaBlendedObjects.Add(sceneObject);
            else
                opaqueObjects.Add(sceneObject);  
        }

        void Objects_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            lock (this)
            {
                if (e.OldItems != null)
                {
                    foreach (SceneObject sceneObject in e.OldItems)
                    {
                        if (sceneObject.NeedAlphaBlending)
                            alphaBlendedObjects.Remove(sceneObject);
                        else
                            opaqueObjects.Remove(sceneObject);

                        sceneObject.PropertyChanged -= sceneObject_PropertyChanged;
                    }
                }

                if (e.NewItems != null)
                {
                    foreach (SceneObject sceneObject in e.NewItems)
                    {
                        AddOrCheckSceneObjectToCorrectList(sceneObject);
                        sceneObject.PropertyChanged += sceneObject_PropertyChanged;
                    }
                }
            }
        }

        void sceneObject_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            lock (this)
            {
                AddOrCheckSceneObjectToCorrectList(sender as SceneObject);
            }
        }
    }
}
